package com.botann.projects.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.botann.projects.base.BaseController;
import com.botann.projects.base.Model;
import com.botann.projects.constants.API;
import com.botann.projects.constants.Constant;
import com.botann.projects.model.Cmd;
import com.botann.projects.model.Version;
import com.botann.projects.service.ProjectsServiceIntf;
import com.botann.projects.utils.alioss.AliOSSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.List;

/**
 * projects
 * ProjectsController
 * Created by 刘山国 on 2020/5/11.
 * Copyright (c) 2017 伯坦科技. All rights reserved
 */
@RestController
public class ProjectsController extends BaseController {
    @Override
    public Class loggerClass() {
        return ProjectsController.class;
    }

    @Autowired
    private ProjectsServiceIntf service;

    /*
     * 添加更新项目
     * @param roleJson String
     * @return Model
     */
    @RequestMapping(value = API.URL_PROJECT_ADD_UPDATE, method = RequestMethod.POST)
    public Model addOrUpdate(@RequestParam String json) {
        try {
            return successModel(Constant.DO_SUCCESS,service.addUpdateProject(json));
        } catch (Exception e) {
            return failureModel(e);
        }
    }

    @RequestMapping(value = API.URL_PROJECTS, method = RequestMethod.POST)
    public Model projects(Integer pageIndex, Integer pageSize) {
        try {
            return successModel(service.loadProjects(pageIndex,pageSize));
        } catch (Exception e) {
            return failureModel(e);
        }
    }


    @RequestMapping(value = API.URL_CMD_ADD_UPDATE, method = RequestMethod.POST)
    public Model addOrUpdateCmd(@RequestParam String json) {
        try {
            service.addUpdateCmd(json);
            return successModel(Constant.DO_SUCCESS);
        } catch (Exception e) {
            return failureModel(e);
        }
    }

    @RequestMapping(value = API.URL_CMDS, method = RequestMethod.POST)
    public Model cmds(Integer projectId) {
        try {
            return successModel(service.loadCmds(projectId));
        } catch (Exception e) {
            return failureModel(e);
        }
    }

    @RequestMapping(value = API.URL_CMD_DELETE, method = RequestMethod.POST)
    public Model delete(String deleteIdsJson) {
        try {
            service.deleteCmds(deleteIdsJson);
            return successModel();
        } catch (Exception e) {
            return failureModel(e);
        }
    }

//    @RequestMapping(value = API.URL_CMD_RUN, method = RequestMethod.POST)
    @RequestMapping(value = "/public/cmd-run", method = RequestMethod.GET)
    public Model cmdRun(String versionJson, String json) {
        try {
            OSS ossClient = new OSSClientBuilder().build(AliOSSUtils.endpoint, AliOSSUtils.accessKeyId, AliOSSUtils.accessKeySecret);

//            Cmd cmd = jsonToModel(json,Cmd.class);
//            Cmd load = service.loadCmd(cmd.getId());
//            Version version = jsonToModel(versionJson,Version.class);
//            if (cmd.getCmd().endsWith(load.getCmd()) && !load.isDel()) {
//                if (cmd.getCmd().endsWith("download")) {
//                    // 创建OSSClient实例。
////                    OSS ossClient = new OSSClient(AliOSSUtils.endpoint,AliOSSUtils.accessKeyId,AliOSSUtils.accessKeySecret);
//
//                    boolean success = AliOSSUtils.download(version.getInfo());
//                    if (success) {
//                        logger.info("下载成功: " + version.getInfo());
//                    }
//                } else  {
//                    List list = runShell(cmd.getCmd());
//                    logger.info(list.toString());
//                }
//
//            }
            return successModel();
        } catch (Exception e) {
            return failureModel(e);
        }
    }
    /**
     * 运行shell
     *
     * @param sh
     *            需要执行的shell
     * @return
     */
    private List runShell(String sh) throws Exception {
        List<String> strList = new ArrayList();

        logger.info(sh);

        Process process;
        process = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c",sh},null,null);
//        process = Runtime.getRuntime().exec(sh);
        InputStreamReader ir = new InputStreamReader(process
                .getInputStream());
        LineNumberReader input = new LineNumberReader(ir);
        String line;
        int exitValue = process.waitFor();
        logger.info(exitValue);
        while ((line = input.readLine()) != null) {
            strList.add(line);
        }

//        Process process = Runtime.getRuntime().exec(sh);
//        int exitValue = process.waitFor();
//        if (0 != exitValue) {
//            logger.error("call shell failed. error code is :" + exitValue);
//        }


//        Runtime rt = Runtime.getRuntime();
//        rt.exec(sh);

        return strList;
    }
}
